// pages/collection/collection.js
const app = getApp();
const AV = require("../../utils/av-weapp-min.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    collectons : [],
    rooms : [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let globalCollects = app.globalData.collections;
    let globalRooms = app.globalData.rooms;
    let tRooms = [];
    for (var i = 0; i < globalRooms.length; i++) {
      let room = globalRooms[i];
      let has = false;
      for (var j = 0; j < globalCollects.length; j++) {
        // console.log("sub, ", room.id, clts[j].attributes.rentId);
        if (globalCollects[j].attributes.rentId == room.id) {
          has = true;
        }
      }
      if (has) {
        tRooms.push(room);
      }
    }
    this.setData({
      collections : app.globalData.collections,
      rooms: tRooms
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  doJump: function (e) { //跳转到详细页面
    console.log("dojump", e);
    let index = e.currentTarget.dataset.index;
    let id = e.target.id;
    let target = this.data.rooms[index];
    let lcUser = AV.User.current();
    let self = this;
    if ("2" === id) {
      console.log("------> onlike icon'd been clicked");
      if (!lcUser) return;
      let clts = this.data.collects;
      for (var i = 0; i < clts.length; i++) {
        if (clts[i].attributes.rentId == target.id) {
          wx.showToast({
            icon: 'none',
            title: '你已经收藏过了',
          });
          return;
        }
      }
      wx.showLoading();
      var Collect = AV.Object.extend('collect');
      var collect = new Collect();
      collect.set('rentId', target.id);
      collect.set("userId", lcUser.id);
      collect.save().then(function (clt) {
        wx.hideLoading();
        self.loadCollect();
        wx.showToast({
          title: '收藏成功!',
        });
      }, function (error) {
        wx.hideLoading();
        self.loadCollect();
        console.error(error);
      });
    } else {
      app.globalData.homeDetail = target;
      // console.log(target);
      wx.navigateTo({
        url: '../home_details/home_details?src=collection',
      })
    }

  },
})